﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace DailyApp.WPF.Extensions
{
    /// <summary>
    /// PassworkBox拓展属性
    /// </summary>
    public class PasswordBoxExtend
    {


        public static string GetPwd(DependencyObject obj)
        {
            return (string)obj.GetValue(PwdProperty);
        }

        public static void SetPwd(DependencyObject obj, string value)
        {
            obj.SetValue(PwdProperty, value);
        }
            
        // Using a DependencyProperty as the backing store for Pwd.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PwdProperty =
            DependencyProperty.RegisterAttached("Pwd", typeof(string), typeof(PasswordBoxExtend), new PropertyMetadata("",OnPwdChanged));
        /// <summary>
        /// 自定义附加属性变化 改变 PasswordBox 的值
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnPwdChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is PasswordBox pwd && (!(e.NewValue?.ToString()??"").Equals(pwd.Password))) {
                pwd.Password = e.NewValue?.ToString() ?? "";
            }
        }
    }
    /// <summary>
    /// Password行为,Password变化，自定义附加属性跟着变化
    /// </summary>
    public class PasswoekBoxHavior : Behavior<PasswordBox> {
      /// <summary>
      /// 附加 注入事件
      /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.PasswordChanged += OnPasswordChangd;
        }
        /// <summary>
        /// Password行为,Password变化，自定义附加属性跟着变化
        /// </summary>
        private void OnPasswordChangd(object sender, RoutedEventArgs e)
        {
            if (sender is PasswordBox pwd) {
                string password = PasswordBoxExtend.GetPwd(pwd);
                if( password!= pwd.Password) PasswordBoxExtend.SetPwd(pwd, pwd.Password);
            }
        }

        /// <summary>
        /// 销毁 移除事件
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.PasswordChanged -= OnPasswordChangd;

        }
    }
}
